package it.ellematica.sampledownloadpdf.struts.action;

import javax.portlet.PortletConfig;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import java.io.OutputStream;

import com.liferay.portal.kernel.portlet.LiferayRenderResponse;
import com.liferay.portal.kernel.servlet.HttpHeaders;
import com.liferay.portal.struts.PortletAction;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

/**
 *
 * @author Raffaello Ursino
 *
 */

public class DownloadPdfAction extends PortletAction{

	private static final boolean _CHECK_METHOD_ON_PROCESS_ACTION = false;
	private Log log = LogFactory.getLog(this.getClass());

	public ActionForward render(ActionMapping mapping, ActionForm form,PortletConfig config, RenderRequest req, RenderResponse res)throws Exception {
		log.debug("DownloadPdfAction - render()");

        String pdfName = (String)req.getParameter("PdfRequestName");

        InputStream ISPdfDocument =Test.class.getResourceAsStream("..\\..\\resources\\"+pdfName);


        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
        byte[] buffer = new byte[1024];
        int len;

        while((len = ISPdfDocument.read(buffer)) >= 0){
            baos.write(buffer, 0, len);
        }
        ISPdfDocument.close();
        baos.close();
        byte[] pdfDocument = baos.toByteArray();

        LiferayRenderResponse liferayRes = (LiferayRenderResponse) res;
        String contentType = "application/pdf";
        String nome= pdfName+".pdf";
        nome=nome.replace(' ','_');
        liferayRes.setContentType(contentType);
//                    liferayRes.addProperty(HttpHeaders.CACHE_CONTROL,"max-age=3600, must-revalidate");
//					liferayRes.setResourceName(nome);
        log.debug("HttpHeaders.CONTENT_DISPOSITION__"+ "attachment; filename=" + nome);
        liferayRes.addProperty(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + nome);
        log.debug("Acquisizione dello stream dalla response");
        OutputStream out = liferayRes.getPortletOutputStream();
        out.write(pdfDocument);
        out.flush();
        out.close();
                   
        
	    ActionForward forward = mapping.findForward("List");
	    return forward;
	}



	/**
	 * Permette l'invocazione della Action tramite un qualsiasi metodo HTTP, e non
	 * solo in POST.
	 *
	 * @see com.liferay.portal.struts.PortletAction#isCheckMethodOnProcessAction()
	 */
	@Override
	protected boolean isCheckMethodOnProcessAction() {

       return _CHECK_METHOD_ON_PROCESS_ACTION;
	}

}
